//
//  XCSMSCountryListViewController.m
//  HOLLASMSLoginKit
//
//  Created by Mars on 2019/10/11.
//  Copyright © 2019 mao PengLin. All rights reserved.
//

#import "XCSMSCountryListViewController.h"
#import "XCSMSCountryListCell.h"

@interface XCSMSCountryListViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong) NSMutableArray<NSArray<XCSMSISOCountry *> *> * countryGroupList;
@property (nonatomic, strong) UITableView *tableView;
@end

@implementation XCSMSCountryListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [XCSMSTheme sharedTheme].backgroundColor;
    
    [self setupUI];

    [self setupDataSource];
}
    
- (void)setupDataSource{
    
    NSArray<XCSMSISOCountry *> * countryList = [XCSMSISOMapper countryList];
    
    _countryGroupList = [self getCountryListGroup:countryList];
    
    [self.tableView reloadData];
}
    
- (void)setupUI{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, HWNavBarHeight, HWScreenWidth, HWScreenHeight - HWNavBarHeight) style:UITableViewStylePlain];
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    [self.view addSubview:self.tableView];
    
    [self.tableView registerClass:[XCSMSCountryListCell class] forCellReuseIdentifier:@"Cell"];
}
    
- (NSMutableArray *)getCountryListGroup:(NSArray<XCSMSISOCountry *> *)arr {
    
    NSMutableSet *set = [NSMutableSet set];
    
    [arr enumerateObjectsUsingBlock:^(XCSMSISOCountry * _Nonnull model, NSUInteger idx, BOOL * _Nonnull stop) {
        [set addObject:model.initial];
    }];
    
    NSArray *sortDesc = @[[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES]];
    NSArray *sortSetArray = [set sortedArrayUsingDescriptors:sortDesc];
    
    __block NSMutableArray *groupArr = [NSMutableArray array];
                           
    [sortSetArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"initial = %@", obj];
        NSArray *tempArr = [NSArray arrayWithArray:[arr filteredArrayUsingPredicate:predicate]];
        [groupArr addObject:tempArr];
    }];
                               
    return groupArr;
                               
}
    
#pragma mark tableViewDelegate && Datasorce
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if ([self IsUSLaguage]){
        return _countryGroupList.count;
    }else{
        return 1;
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if ([self IsUSLaguage]){
        return _countryGroupList[section].count;
    }else{
        return [XCSMSISOMapper countryList].count;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 46;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    XCSMSCountryListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if ([self IsUSLaguage]){
        [cell setContent:self.countryGroupList[indexPath.section][indexPath.row]];
    }else{
        [cell setContent:[XCSMSISOMapper countryList][indexPath.row]];
    }
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if ([self IsUSLaguage]){
        return 48;
    }else{
        return 0;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, HWScreenWidth, 48)];
    header.backgroundColor = [XCSMSTheme sharedTheme].backgroundColor;
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(16, 0, HWScreenWidth - 32, 48)];
    label.text = _countryGroupList[section].firstObject.initial;
    label.textAlignment = NSTextAlignmentNatural;
    label.textColor = [XCSMSTheme sharedTheme].countryListHeaderTextColor;
    label.font = DemiBoldFont(16);
    [header addSubview:label];
    return header;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectBlock){
        if ([self IsUSLaguage]){
            self.selectBlock(_countryGroupList[indexPath.section][indexPath.row]);
        }else{
            self.selectBlock([XCSMSISOMapper countryList][indexPath.row]);
        }
    }
    [self.navigationController popViewControllerAnimated:true];
}

- (BOOL)IsUSLaguage {
    if (SupportMultiLanguages()) {
        NSArray *appLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
        NSString *languageName = [appLanguages objectAtIndex:0];
        if ([languageName rangeOfString:@"en"].location != NSNotFound){
            return YES;
        }else{
            return NO;
        }
    } else {
        return YES;
    }
}
                               
@end
